package com.x.ant.service;

import com.x.ant.dao.DeptDao;
import com.x.ant.dao.UserDao;
import com.x.ant.manage.DeptManage;
import com.x.ant.model.Dept;
import com.x.ant.model.DeptUser;
import com.x.ant.model.Staff;
import com.x.ant.model.User;
import com.x.ant.util.CodeUtil;
import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class DeptService extends BaseService {
    @Autowired
    private DeptDao deptDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private DeptManage deptManage;

    public List<Dept> selectDeptList(Dept dept) {
        try {
            return deptDao.selectDeptList(dept);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public List<DeptUser> selectDeptUserList(Dept dept) {
        try {
            List<Dept> deptList = deptDao.selectDeptList(dept);
            User user = new User();
            user.setUserType(1);
            List<Staff> staffList;
            List<DeptUser> deptUserList = new ArrayList<DeptUser>();
            Staff staff = new Staff();
            staff.setStaffType(1);
            for (Dept d : deptList) {
                DeptUser deptUser = new DeptUser();
                deptUser.setDeptId(d.getDeptId());
                staff.setDeptId(d.getDeptId());
                staff.setUser(user);
                staffList = userDao.selectStaffList(staff);
                if (staffList.size() > 0) {
                    deptUser.setUser(staffList.get(0).getUser());
                }
                deptUser.setDept(d);
                deptUserList.add(deptUser);
            }
            return deptUserList;
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public List<Dept> selectDeptByUser(DeptUser deptUser) {
        try {
            return deptDao.selectDeptUserList(deptUser);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public void insertDept(Dept dept) {
        try {
            deptManage.insertDept(dept);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public void updateDept(Dept dept) {
        try {
            deptManage.updateDept(dept);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

}
